package com.jiejie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiejie.commons.ServerResponse;
import com.jiejie.entity.Movie;
import com.jiejie.entity.Order;
import com.jiejie.entity.Schedule;
import com.jiejie.mapper.MovieMapper;
import com.jiejie.mapper.OrderMapper;
import com.jiejie.mapper.ScheduleMapper;
import com.jiejie.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 辰广
 * @since 2022-10-05
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Resource
    private OrderMapper mapper;

    @Resource
    private ScheduleMapper scheduleMapper;

    @Resource
    private MovieMapper movieMapper;
    @Override
    public Order getById(int orderId) {
        return mapper.selectById(orderId);
    }

    @Override
    public int saveCOrder(Order order) {
        return mapper.insert(order);
    }

    @Override
    public int updateOrder(Order order) {

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",order.getOrderId());
        return mapper.update(order,wrapper);

    }

    @Override
    public int deleteById(int orderId) {
        return mapper.deleteById(orderId);
    }

    @Override
    public Map<Order,List<Object>> getOrderAndSchedule(Integer customerId) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("customer_id",customerId);
        wrapper.eq("order_version",0);
        wrapper.orderByDesc("order_createtime");
        List<Order> order = mapper.selectList(wrapper);
        Map<Order,List<Object>> map = new LinkedHashMap<>();
        for (int i=0; i<order.size(); i++){
            Schedule schedule = scheduleMapper.selectById(order.get(i).getScheduleId());
            Movie movie = movieMapper.selectById(schedule.getMovieId());
            List<Object> list = new ArrayList<>();
            list.add(schedule);
            list.add(movie);

            map.put(order.get(i),list);
        }
        return map;
    }

    @Override
    public Order getOrderByOrderNum(String OrderNum) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("order_num",OrderNum);
        return mapper.selectOne(wrapper);
    }

    @Override
    public int delOrder(Integer orderId) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",orderId);
        Order order = mapper.selectById(orderId);
        order.setOrderVersion(1);
        return mapper.update(order,wrapper);
    }
}
